# server.py
import socket
from cryptography.fernet import Fernet

# 必须与客户端使用相同的合法密钥
KEY = b'2DArf8mfLdgsDgwdnBQ5Uzr9zIRSEVerCnVk8Mn9xTQ='

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("127.0.0.1", 8848))
server_socket.listen(5)
cipher = Fernet(KEY)  # 使用合法密钥初始化加密器

print("等待连接...")
client_socket, address = server_socket.accept()
print(f"收到来自 {address[0]}:{address[1]} 的连接")

while True:
    encrypted_data = client_socket.recv(1024)
    if not encrypted_data:
        break

    try:
        decrypted_data = cipher.decrypt(encrypted_data).decode("utf-8")  # 解密消息
    except:
        print("解密失败！连接已终止")
        break

    print(f"收到消息：{decrypted_data}")

    if decrypted_data == "exit":
        break

    reply = input("输入回复：")
    encrypted_reply = cipher.encrypt(reply.encode("utf-8"))  # 加密回复
    client_socket.send(encrypted_reply)

client_socket.close()